/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.demotestoh.slice;

import com.example.demotestoh.ResourceTable;
import com.example.demotestoh.bean.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.bundle.ElementName;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationSlot;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;
import okhttp3.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel hilog = new HiLogLabel(HiLog.DEBUG ,0x0000, "test0002");
    CookingRecord transcribe_data = null;
    ProgressBar progressBar;
    long transcribe_date=0;
    SockerTest test1;
    Text tx ;
    Text tx_s ;
    NotificationSlot slot;
    Preferences preferences;
    ListData listData;
    int inSetValue = 0;                             //火力
    boolean flagswitch = false;                     //开关状态
    boolean flag_transcribe = false;                //录制状态

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        tx= (Text) findComponentById(ResourceTable.Id_text01);
        Button btsub = (Button) findComponentById(ResourceTable.Id_buttonsub);
        Button btswitch = (Button) findComponentById(ResourceTable.Id_buttonswitch);
        Button btadd = (Button) findComponentById(ResourceTable.Id_buttonadd);
        Button btTranscribeStart = (Button) findComponentById(ResourceTable.Id_transcribeStart);
        Button btTranscribeEnd = (Button) findComponentById(ResourceTable.Id_transcribeEnd);
        Button btdownload = (Button) findComponentById(ResourceTable.Id_download);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progressbar);
        tx_s = (Text) findComponentById(ResourceTable.Id_time_s);

        List<CookingRecord> list = getData();   //获取本地数据
        listData=new ListData(list,this);
        listContainer.setItemProvider(listData);


        slot = new NotificationSlot("slot_001","slot_default", NotificationSlot.LEVEL_DEFAULT);
        slot.setDescription("NotificationSlotDescription");
        try {
            NotificationHelper.addNotificationSlot(slot);
        } catch (RemoteException ex) {
            HiLog.warn(hilog, "addNotificationSlot occur exception.");
        }

        //运行
        listContainer.setItemClickedListener((container, component, position, id) -> {
            CookingRecord item = (CookingRecord) listContainer.getItemProvider().getItem(position);
            runCooking(item);
        });
        //删除
        listContainer.setItemLongClickedListener((container, component, position, id) -> {
            listData.list.remove(position);
            new ToastDialog(this)
                    .setText("you long clicked: remove ok!")
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
            return false;
        });

        //下载美食火候
        btdownload.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                CommonDialog dialog = new CommonDialog(getContext());
                Component container = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_share, null, false);
                ((Text) container.findComponentById(ResourceTable.Id_text_share)).setText("下载美食火候");
                ((Button) container.findComponentById(ResourceTable.Id_buttonok)).setText("下载");
                ((Button) container.findComponentById(ResourceTable.Id_buttonok)).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {

                            httpposts(listData,((TextField)container.findComponentById(ResourceTable.Id_text_field)).getText());
                        new ToastDialog(getContext())
                                .setText("正在下载！")
                                // Toast显示在界面中间
                                .setAlignment(LayoutAlignment.CENTER)
                                .show();
                        dialog.destroy();
                    }
                });
                ((Button) container.findComponentById(ResourceTable.Id_buttonoff)).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        dialog.destroy();
                    }
                });
                dialog.setContentCustomComponent(container);
                dialog.setAlignment(LayoutAlignment.CENTER);
                dialog.setSize(800, 700);
                dialog.setCornerRadius(100);
                dialog.show();
            }
        });

        //录制美食火候
        btTranscribeStart.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                if(!flag_transcribe) {
                    CommonDialog dialog = new CommonDialog(getContext());
                    Component container = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_share, null, false);
                    ((Text) container.findComponentById(ResourceTable.Id_text_share)).setText("火候录制");
                    ((TextField) container.findComponentById(ResourceTable.Id_text_field)).setHint("请输入录制名字");
                    ((Button) container.findComponentById(ResourceTable.Id_buttonok)).setText("开始录制");
                    ((Button) container.findComponentById(ResourceTable.Id_buttonok)).setClickedListener(new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {
                            transcribe_data = new CookingRecord();
                            transcribe_data.setName(((TextField) container.findComponentById(ResourceTable.Id_text_field)).getText());
                            transcribe_date = System.currentTimeMillis();
                            flag_transcribe = true;
                            if (!flagswitch) {
                                test1.sockerSend(1, 0, 0);
                            } else {
                                transcribe_data.sheetAdd(inSetValue, 0);
                            }

                            dialog.destroy();
                        }
                    });
                    ((Button) container.findComponentById(ResourceTable.Id_buttonoff)).setClickedListener(new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {
                            dialog.destroy();
                        }
                    });
                    dialog.setContentCustomComponent(container);
                    dialog.setAlignment(LayoutAlignment.CENTER);
                    dialog.setSize(800, 700);
                    dialog.setCornerRadius(100);
                    dialog.show();
                }else{
                    flag_transcribe = false;
                    transcribe_data.sheetAdd(4,(System.currentTimeMillis()-transcribe_date)/100);
                    listData.list.add(transcribe_data);
                    test1.sockerSend(1,0,0);
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            listData.notifyDataChanged();
                        }
                    });
                }



            }
        });

        //定时关火
        btTranscribeEnd.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                //定时
                CommonDialog dialog = new CommonDialog(getContext());
                Component container = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_share, null, false);
                ((Text) container.findComponentById(ResourceTable.Id_text_share)).setText("定时");
                ((TextField) container.findComponentById(ResourceTable.Id_text_field)).setHint("输入定时时间     单位秒");
                ((Button) container.findComponentById(ResourceTable.Id_buttonok)).setText("开始定时");
                ((Button) container.findComponentById(ResourceTable.Id_buttonok)).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        timingCook(Integer.parseInt(((TextField) container.findComponentById(ResourceTable.Id_text_field)).getText()));
                        dialog.destroy();
                    }
                });
                ((Button) container.findComponentById(ResourceTable.Id_buttonoff)).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        dialog.destroy();
                    }
                });
                dialog.setContentCustomComponent(container);
                dialog.setAlignment(LayoutAlignment.CENTER);
                dialog.setSize(800, 700);
                dialog.setCornerRadius(100);
                dialog.show();
            }
        });

        //档位减
        btsub.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                test1.sockerSend(3,inSetValue-1,0);
            }
        });
        //开关智能电饼铛
        btswitch.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                test1.sockerSend(1,0,0);
            }
        });
        //档位加
        btadd.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                test1.sockerSend(3,inSetValue+1,0);
            }
        });


        try {
            test1 = new SockerTest(MainAbilitySlice.this);
            test1.start();
            Thread.sleep(200);
            test1.sockerSend(5,0,0);
        } catch (Exception e) {
            HiLog.debug(hilog,"erorr!"+e,"");
        }
    }

    private void httpgets()
    {
        String url = "http://192.168.0.145:5000/CookingRecord_add";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HiLog.debug(hilog, "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                HiLog.debug(hilog, "onResponse: " + response.body().string());
            }
        });
    }
    //下载美食火候
    public void httpposts(ListData listData,String id)
    {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = "{\"id\":\""+id+"\"}";
        Request request = new Request.Builder()
                .url("http://192.168.0.145:5000/CookingRecord_get")
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HiLog.debug(hilog, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                HiLog.debug(hilog, response.protocol() + " " +response.code() + " " + response.message());
                //HiLog.debug(hilog, "onResponse: " + response.body().string());
                Gson gson = new Gson();
                CookingRecord dd = gson.fromJson(response.body().string(),CookingRecord.class);
                listData.list.add(dd);
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        listData.notifyDataChanged();
                    }
                });
            }
        });
    }

    //获取本地美食数据
    private ArrayList<CookingRecord> getData() {
        Gson gson = new Gson();
        Type types = new TypeToken<ArrayList<CookingRecord>>() {}.getType();
        ArrayList<CookingRecord> data;
        Context context = getApplicationContext();
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        String fileName = "test_pref";
        preferences = databaseHelper.getPreferences(fileName);

        String value = preferences.getString("buf","no");

        HiLog.debug(hilog, "buf: " + value);



        String listJsonStrs="[" +
                "{\"name\":\"糖醋里脊\",\"id\":\"\",\"sheet\":[{\"heatControl\":1,\"time\":10},{\"heatControl\":2,\"time\":40},{\"heatControl\":3,\"time\":70},{\"heatControl\":1,\"time\":130},{\"heatControl\":2,\"time\":160},{\"heatControl\":3,\"time\":190},{\"heatControl\":4,\"time\":210}]}," +
                "{\"name\":\"土豆虾球\",\"id\":\"\",\"sheet\":[{\"heatControl\":1,\"time\":10},{\"heatControl\":2,\"time\":40},{\"heatControl\":3,\"time\":70},{\"heatControl\":1,\"time\":130},{\"heatControl\":2,\"time\":160},{\"heatControl\":3,\"time\":190},{\"heatControl\":4,\"time\":210}]}," +
                "{\"name\":\"青菜肉圆\",\"id\":\"\",\"sheet\":[{\"heatControl\":1,\"time\":10},{\"heatControl\":2,\"time\":40},{\"heatControl\":3,\"time\":70},{\"heatControl\":1,\"time\":130},{\"heatControl\":2,\"time\":160},{\"heatControl\":3,\"time\":190},{\"heatControl\":4,\"time\":210}]}," +
                "{\"name\":\"红烧羊肉\",\"id\":\"\",\"sheet\":[{\"heatControl\":1,\"time\":10},{\"heatControl\":2,\"time\":40},{\"heatControl\":3,\"time\":70},{\"heatControl\":1,\"time\":130},{\"heatControl\":2,\"time\":160},{\"heatControl\":3,\"time\":190},{\"heatControl\":4,\"time\":210}]}," +
                "{\"name\":\"腐竹炒肉\",\"id\":\"\",\"sheet\":[{\"heatControl\":1,\"time\":10},{\"heatControl\":2,\"time\":40},{\"heatControl\":3,\"time\":70},{\"heatControl\":1,\"time\":130},{\"heatControl\":2,\"time\":160},{\"heatControl\":3,\"time\":190},{\"heatControl\":4,\"time\":210}]}," +
                "{\"name\":\"玉米鸡排\",\"id\":\"\",\"sheet\":[{\"heatControl\":1,\"time\":10},{\"heatControl\":2,\"time\":40},{\"heatControl\":3,\"time\":70},{\"heatControl\":1,\"time\":130},{\"heatControl\":2,\"time\":160},{\"heatControl\":3,\"time\":190},{\"heatControl\":4,\"time\":210}]}" +
                "]";
        if(value.equals("no"))
        {
            data = gson.fromJson(listJsonStrs,types);
        }else{
            data = gson.fromJson(value,types);
        }

        return data;
    }

    //美食烹饪执行函数
    private void runCooking (CookingRecord cookingRecord){
        new Thread(new Runnable() {
            @Override
            public void run()
            {
                try {
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setProgressValue(0);
                            progressBar.setMaxValue((int)(((cookingRecord.getSheet()).get(cookingRecord.getSheet().size()-1)).getTime()/10));
                            tx_s.setText(""+(int)(((cookingRecord.getSheet()).get(cookingRecord.getSheet().size()-1)).getTime()/10));
                        }
                    });
                    int t = 0;
                    for(Item data:cookingRecord.getSheet())
                    {
                        while (data.getTime() != t)
                        {

                                Thread.sleep(100);

                            t++;
                        }

                        progressBar.setProgressValue((int)(data.getTime()/10));
                        //tx_s.setText((int)((cookingRecord.getSheet().get(cookingRecord.getSheet().size()-1)).getTime()/10));

                        if(data.getHeatControl() == 4)
                        {
                            test1.sockerSend(1,0,0);
                            int notification_id = 1;
                            NotificationRequest request = new NotificationRequest(notification_id);
                            request.setSlotId(slot.getId());

                            String title = "智能电饼铛";
                            String text = cookingRecord.getName()+"已烹饪完成!";
                            NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
                            content.setTitle(title)
                                    .setText(text);
                            NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
                            // 设置通知的小图标
                            //request.setLittleIcon(PixelMap);
                            // 设置通知的内容
                            request.setContent(notificationContent);

                            ElementName elementName = new ElementName("", "com.example.testintentagent", "com.example.testintentagent.IntentAgentAbility");
                            // 将ElementName字段添加到Intent中
                            Intent intent = new Intent();
                            intent.setElement(elementName);
                            List<Intent> intentList = new ArrayList<>();
                            intentList.add(intent);
                            // 指定启动一个有页面的ability
                            IntentAgentInfo intenAgentinfo = new IntentAgentInfo(request.getNotificationId(), IntentAgentConstant.OperationType.START_ABILITY, IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG, intentList, null);
                            // 获取IntentAgent实例
                            IntentAgent intentAgent = IntentAgentHelper.getIntentAgent(getContext(), intenAgentinfo);
                            request.setIntentAgent(intentAgent);
                            request.setTapDismissed(true);


                            NotificationHelper.publishNotification(request);


                            break;
                        }

                        if(flagswitch){
                            test1.sockerSend(3,data.getHeatControl(),0);
                        }else{
                            test1.sockerSend(1,0,0);
                            Thread.sleep(100);
                            test1.sockerSend(3,data.getHeatControl(),0);
                        }
                    }
                } catch (Exception e) {
                    HiLog.debug(hilog,"erorr!"+e,"");
                }
            }
        }).start();
    }

    //定时执行函数
    private void timingCook (int time_s){
        new Thread(new Runnable() {
            @Override
            public void run()
            {
                try {

                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setProgressValue(0);
                            progressBar.setMaxValue(time_s);
                            tx_s.setText(""+time_s);
                        }
                    });

                    for(int i=0;i<=time_s;i++) {
                        Thread.sleep(1000);
                        int finalI = i;
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setProgressValue(finalI);
                            }
                        });
                    }
                    if(flagswitch)
                    {
                        test1.sockerSend(1,0,0);
                        flagswitch = false;
                    }

                    int notification_id = 1;
                    NotificationRequest request = new NotificationRequest(notification_id);
                    request.setSlotId(slot.getId());

                    String title = "智能电饼铛";
                    String text = "定时烹饪完成!";
                    NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
                    content.setTitle(title)
                            .setText(text);
                    NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
                    // 设置通知的小图标
                    //request.setLittleIcon(PixelMap);
                    // 设置通知的内容
                    request.setContent(notificationContent);

                    ElementName elementName = new ElementName("", "com.example.testintentagent", "com.example.testintentagent.IntentAgentAbility");
                    // 将ElementName字段添加到Intent中
                    Intent intent = new Intent();
                    intent.setElement(elementName);
                    List<Intent> intentList = new ArrayList<>();
                    intentList.add(intent);
                    // 指定启动一个有页面的ability
                    IntentAgentInfo intenAgentinfo = new IntentAgentInfo(request.getNotificationId(), IntentAgentConstant.OperationType.START_ABILITY, IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG, intentList, null);
                    // 获取IntentAgent实例
                    IntentAgent intentAgent = IntentAgentHelper.getIntentAgent(getContext(), intenAgentinfo);
                    request.setIntentAgent(intentAgent);
                    request.setTapDismissed(true);

                    try {
                        NotificationHelper.publishNotification(request);
                    } catch (RemoteException ex) {
                        HiLog.warn(hilog, "publishNotification occur exception.");
                    }

                } catch (Exception e) {
                    HiLog.debug(hilog,"erorr!"+e,"");

                }

            }
        }).start();
    }



    //Socker 接收回调函数
    public void sockerCallback(byte[] data) {
        HiLog.debug(hilog,""+(int)data[0]+" "+data[1]+" "+data[2]+" "+data[3],"");
        if((int)data[0] == -86)//接收处理
        {
            switch (data[1])
            {
                case 20:flagswitch=(data[2] == 1);break;

                case 21:inSetValue=(int)data[2];break;

                case 22:flagswitch=(data[2] == 1);inSetValue=(int)data[3];if(flag_transcribe){transcribe_data.sheetAdd(inSetValue,(System.currentTimeMillis()-transcribe_date)/100); };break;
            }
            getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    tx.setText(inSetValue+"");
                }
            });

            HiLog.debug(hilog,"ok "+inSetValue);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Gson gson = new Gson();
        preferences.putString("buf",gson.toJson(listData.list));
        preferences.flush();//数据本地化
    }

    @Override
    protected void onBackground() {
        super.onBackground();
        Gson gson = new Gson();
        preferences.putString("buf",gson.toJson(listData.list));
        preferences.flush();//数据本地化
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


}
